import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-08-12
 * Time: 20:43
 */
public class Jdbcdemo2 {
    public static void main(String[] args) throws SQLException { //这里请求服务器连接, 有可能会被服务器拒绝所以抛异常
        //1.创建数据源, 即找到数据库
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java117?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("201754ljj");
        //2.和数据库服务器进行网络连接
        Connection connection = dataSource.getConnection();
        //3.构造SQL语句
        String sql = "select* from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql); //预处理SQL语句, 并发送给我服务器处理
        //4.查询
        ResultSet resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println(id + " " + name);
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();


    }
}
